//
//  RecommendViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/8/27.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "RecommendViewController.h"
#import "user_myProductViewController.h"
#import "ProductModel.h"
#import "ProductDetailsViewController.h"
#import "RecommendCell.h"

@interface RecommendViewController () <RecommendDelegate>

@property (nonatomic, strong) NSArray *jsonArray;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *recommendArray;

@end

static NSString *RecommendCellIndetifier = @"RecommendCell";

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleView:@"我的推款"];
    //右侧按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"我要推款" style:UIBarButtonItemStyleBordered target:self action:@selector(recommend)];
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    footerView.backgroundColor = [UIColor whiteColor];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(SCREEN_WIDTH-120, 40, 80, 40);
    [cancelButton setImage:[UIImage imageNamed:@"user_myRcommond_cancelButton"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:cancelButton];
    self.tableView.tableFooterView = footerView;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendCell" bundle:nil] forCellReuseIdentifier:RecommendCellIndetifier];
    _recommendArray = [NSMutableArray array];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestData];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)requestData {
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"type":@"5", @"productType":@"",@"productStyle":@"",@"designerId":@""};
    [RequestData requestProductParameters:[UIUtil toJsonString:dic] withBlock:^(NSArray *jsonArray, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
            }
        } else {
            self.jsonArray = jsonArray;
            [self.tableView reloadData];
        }
    }];
}

- (void)recommend {
    user_myProductViewController *view = [[user_myProductViewController alloc] init];
    [self.navigationController pushViewController:view animated:YES];
}

- (void)cancel {
    if (!(_recommendArray.count > 0)) {
        [[ESHUDView sharedInstance] showErrorMessage:@"还没有选择产品" dismissBlock:nil];
        return;
    }
    for (int i=0; i<self.recommendArray.count; i++) {
        if (i==0) {
            dispatch_queue_t queue = dispatch_queue_create("QuDetailQueue", DISPATCH_QUEUE_SERIAL);
            dispatch_async(queue, ^{
                [self requestCancle:i];
            });
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                });
                [self requestCancle:i];
            });
        }
    }
}

- (void)requestCancle:(NSInteger)i{
    ProductModel *model = _recommendArray[i];
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"productId":model.productId==nil?@"":model.productId,@"type":@"0"};
    [RequestData productApply:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"下架失败":msg dismissBlock:nil];
            }
        } else {
            [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
            NSMutableArray *array = [NSMutableArray arrayWithArray:self.jsonArray];
            for (int i=0; i<_jsonArray.count; i++) {
                if ([((ProductModel*)_jsonArray[i]).productId isEqualToString:model.productId]) {
                    [array removeObjectAtIndex:i];
                    self.jsonArray = array;
                    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
                    return;
                }
            }
        }
    }];
}

#pragma mark - tableView Delegate && DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.jsonArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RecommendCell *cell = [self.tableView dequeueReusableCellWithIdentifier:RecommendCellIndetifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[RecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RecommendCellIndetifier];
    }
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.model = [self.jsonArray objectAtIndex:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ProductDetailsViewController *view = [[ProductDetailsViewController alloc] init];
    view.productId = ((ProductModel *)[_jsonArray objectAtIndex:indexPath.row]).productId;
    view.productStatus = ((ProductModel *)[_jsonArray objectAtIndex:indexPath.row]).productStatus;
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.navigationController pushViewController:view animated:YES];
}

- (void)didSelectCheckButtonAtIndexPath:(NSIndexPath *)indexPath ifcheck:(BOOL)ifcheck {
    ProductModel *model = self.jsonArray[indexPath.row];
    if (ifcheck) {
        [_recommendArray addObject:model];
    } else {
        for (int i=0; i<_recommendArray.count; i++) {
            if ([((ProductModel *)_recommendArray[i]).productId isEqualToString:model.productId]) {
                [_recommendArray removeObjectAtIndex:i];
            }
        }
    }
}

@end
